package pkg

import "github.com/golang-jwt/jwt/v4"

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体

//生成JwtToken

func GetJwtToken(secretKey string, iat, seconds int64, payload string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

//验证 token

func ParseJwtToken1(secretKey string, tokenStr string) (payload string, err error) {
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	//if err != nil {
	//	fmt.Println(err)
	//	return "", err
	//}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims["payload"].(string), nil
	} else {
		return "", err
	}
}
